package smartcase.base.log;

import smartcase.base.ConfigurationDefine;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;

import static smartcase.base.ApplicationContextProviderKt.ctxIsStarted;
import static smartcase.base.ApplicationContextProviderKt.getBean;

final class LogReporter {

  private static final LinkedBlockingQueue<LogStruct> LOG_QUEUE = new LinkedBlockingQueue<>();

  private static final ExecutorService REPORT_LOG_EXECUTOR = Executors.newSingleThreadExecutor();

  static {
    REPORT_LOG_EXECUTOR.submit(
        () -> {
          for (; ; ) {
            if (ctxIsStarted()) break;
          }
          ConfigurationDefine define;
          if ((define = getBean(ConfigurationDefine.class)) == null) return;
          Consumer<LogStruct> logConsumer;
          if ((logConsumer = define.getLogConsumer()) == null) return;

          for (; ; ) {
            try {
              logConsumer.accept(LOG_QUEUE.take());
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        });
  }

  static void submitLog(LogStruct log) {
    try {
      LOG_QUEUE.put(log);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
